package store

import (
	"errors"
	"fmt"
	"github.com/jinzhu/gorm"
)

func (u *UserLoginReq) Valid() bool {
	return u.Username != "" && u.Password != ""
}

type UserLoginReq struct {
	Username string `json:"username"`
	Password string `json:"password"`
}
type UpdateUserProfileReq struct {
	Nickname  string `json:"nickName"`
	Gender    uint8  `json:"gender"`
	AvatarURL string `json:"avatarUrl"`
}

type User struct {
	ID       uint64 `json:"uid" gorm:"type:bigint;primary_key;unique_index"`
	Username string `json:"username" gorm:"type:varchar(128);unique;not null"` // 教务的用户名
	Password string `json:"password" gorm:"type:varchar(256)"`                 //教务密码

}

type IUserService interface {
	Login(req UserLoginReq) error
}

// userService 引入 session控制器使用
type userService struct {
	db *gorm.DB
}

var _ IUserService = (*userService)(nil)

// NewUserService 返回一个UserModel的服务
func NewUserService(db *gorm.DB) IUserService {
	return &userService{db: db}
}

func (u *userService) Login(req UserLoginReq) error {
	var user User

	fmt.Println(req)

	//u.db.Table("users").First(&user)
	u.db.Table("users").Where("username = ?", req.Username).First(&user)

	fmt.Println(user)

	if user.Username == "" {
		return errors.New("user not exists")
	}

	if user.Password != req.Password {
		return errors.New("password incorrect")
	}
	return nil
}
